package com.zwl.service.impl;

import java.util.List;
import java.util.Map;

import com.zwl.dao.DeptDao;
import com.zwl.dao.UserDao;
import com.zwl.dao.UserDetailDao;
import com.zwl.dao.impl.DeptDaoImpl;
import com.zwl.dao.impl.UserDaoImpl;
import com.zwl.dao.impl.UserDetailDaoImpl;
import com.zwl.po.PageBean;
import com.zwl.po.RolePo;
import com.zwl.po.UserDetailPo;
import com.zwl.po.UserPo;
import com.zwl.service.UserService;

public class UserServiceImpl implements UserService {
	private UserDao userDao=new UserDaoImpl();
	private UserDetailDao userDetailDao=new UserDetailDaoImpl();
	private DeptDao deptDao=new DeptDaoImpl();
	
	@Override
	public List<UserPo> findByCondition(Map<String, Object> map) {
		List<UserPo> userList=userDao.findByCondition(map);
		if(userList!=null && userList.size()>0){
			for(UserPo user:userList){
				user.setUserDetail(userDetailDao.findbyId(user.getId()));
				if(user.getUserDetail()!=null && user.getUserDetail().getDeptId()!=null){
					user.getUserDetail().setDept(deptDao.findbyId(user.getUserDetail().getDeptId()));
				}
			}
		}
		return userList;
	}

	@Override
	public UserPo findbyId(Integer id) {
		UserPo user=userDao.findbyId(id);
		if(user!=null){
			user.setUserDetail(userDetailDao.findbyId(user.getId()));
			if(user.getUserDetail()!=null && user.getUserDetail().getDeptId()!=null){
				user.getUserDetail().setDept(deptDao.findbyId(user.getUserDetail().getDeptId()));
			}
		}
		return user;
	}

	@Override
	public Integer[] saveUser(UserPo entity) {
		Integer[] results=userDao.saveUser(entity);
		Integer rows=results[0];
		Integer primaryKey=results[1];
		
		entity.getUserDetail().setUserId(primaryKey);
		userDetailDao.saveUserDetail(entity.getUserDetail());
		return results;
	}

	@Override
	public int updateUser(UserPo entity) {
		Integer rows=userDao.updateUser(entity);
		userDetailDao.updateUserDetail(entity.getUserDetail());
		userDao.deleteUserRole(entity.getId(), null);
		
		if(entity.getRoleList()!=null && entity.getRoleList().size()>0){
			for(RolePo role:entity.getRoleList()){
				userDao.saveUserRole(entity.getId(), role.getId());
			}
		}
		return rows;
	}

	@Override
	public PageBean<UserDetailPo> findPageByCondition(int pageIndex, int pageSize, Map<String, Object> map) {
		PageBean<UserDetailPo> pagebean=userDetailDao.findPageByCondition(pageIndex, pageSize, map);
		return pagebean;
	}
	
}
